<?php

namespace App\Http\Controllers\Admin;

use App\Models\Cate as CateModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class Cate extends Controller
{
    //栏目列表
    public function all()
    {
        $cates = CateModel::orderBy('sort', 'asc')->paginate(10);
        $viewData = [
            'cates' =>$cates
        ];
        return view('admin.cate.list', $viewData);
    }

    //栏目添加
    public function add()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['catename', 'sort']);
            $result = (new CateModel)->add($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '添加成功',
                    'url' => url('admin/catelist')
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        return view('admin.cate.add');
    }

    //栏目排序
    public function sort()
    {
        $data = request()->only(['id', 'sort']);
        $result = (new CateModel)->sort($data);
        if ($result == 1) {
            $msg = [
                'code' => 1,
                'msg' => '排序成功',
                'url' => url('admin/catelist')
            ];
        }else {
            $msg = [
                'code' => 0,
                'msg' => $result
            ];
        }
        return $msg;
    }

    //栏目编辑
    public function edit()
    {
        if (request()->isMethod('post')) {
            $data = request()->only(['id', 'catename']);
            $result = (new CateModel)->edit($data);
            if ($result == 1) {
                $msg = [
                    'code' => 1,
                    'msg' => '修改成功',
                    'url' => url('admin/catelist')
                ];
            }else {
                $msg = [
                    'code' => 0,
                    'msg' => $result
                ];
            }
            return $msg;
        }
        $cateInfo = CateModel::find(request('id'));
        $viewData = [
            'cateInfo' => $cateInfo
        ];
        return view('admin.cate.edit', $viewData);
    }

    //栏目删除
    public function del()
    {
        $cateInfo = CateModel::with('articles', 'articles.comments')->find(request('id'));
        foreach($cateInfo->articles as $vo) {
            foreach($vo->comments as $comment) {
                $comment->delete();
            }
            $vo->delete();
        }
        $result = $cateInfo->delete();
        if ($result) {
            $msg = [
                'code' => 1,
                'msg' => '删除成功',
                'url' => url('admin/catelist')
            ];
        }else {
            $msg = [
                'code' => 0,
                'msg' => '删除失败'
            ];
        }
        return $msg;
    }
}
